<template>
  <div>
    <el-dialog
      v-model.sync="dialogVisible"
      :title="title"
      width="60%"
      :before-close="beforeClose"
      @open="initData"
    >
      <el-form
        ref="ref"
        :model="form"
        label-width="120px"
        :rules="{
          category_ids: [{ required: true, message: '请选择类别', trigger: 'blur' }],
          match_date: [{ required: true, message: '请选择赛程日期', trigger: 'blur' }],
          title: [{ required: true, validator: (rule, value, callback) => detectionText(rule, value, callback), trigger: 'blur' }],
          expires_time: [{ required: true, message: '请选择过期时间', trigger: 'blur' }],
          // match_info: [{ required: true, message: '请选择赛程', trigger: 'blur' }],
          match_nick: [{ required: true, message: '请输入赛程', trigger: 'blur' }],
          seckill_price: [{ required: true, message: '请输入秒杀价格', trigger: 'blur' }],
          seckill_expire: [{ required: true, message: '请选择秒杀时间', trigger: 'change' }],
          match_data: [{ required: true, message: '请选择图表赛程', trigger: 'change' }],
          price: [
            {
              required: true,
              validator: (rule, value, callback) => amount(rule, value, callback),
              trigger: 'blur'
            }
          ]
        }"
      >
        <el-form-item label="类别" prop="category_ids">
          <el-radio-group v-model="category_ids" class="" @change="getMatch">
            <el-radio :value="3" size="large">足球</el-radio>
            <el-radio :value="4" size="large">篮球</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赛程日期" prop="match_date">
          <!-- <el-date-picker
            v-model="form.match_date"
            type="date"
            placeholder="请选择赛程日期"
            :clearable="false"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="getMatch"
          /> -->
          <el-radio-group v-model="form.match_date" @change="getMatch">
            <el-radio :label="today">今天</el-radio>
            <el-radio :label="tomorrow">明天</el-radio>
            <el-radio :label="theday">后天</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入方案标题"
            clearable
            type="textarea"
            onkeydown="if(event.keyCode == 32 || event.keyCode == 13)return false;"
            autosize
            style="width: 220px"
            @change="
              () => {
                form.name = form.title
              }
            "
          />
        </el-form-item>
        <!-- prop="match_info" -->
        <el-form-item label="赛程" prop="match_nick">
          <el-select
            v-model="form.match_info"
            filterable
            clearable
            placeholder="请选择赛程"
            :disabled="checked"
            @change="handleMatchChange"
            @clear="
              () => {
                form.match_info = ''
                form.match_nick = ''
                form.expires_time = ''
                historyMatchInfo = {
                  match_info: '',
                  match_nick: '',
                  expires_time: ''
                }
                getMatch()
              }
            "
            style="width: 220px"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-checkbox style="margin: 0 10px" v-model="checked" @change="handleCheckBox"
            >自定义</el-checkbox
          >
          <el-input
            v-if="checked"
            v-model="form.match_nick"
            :disabled="form.match_info ? true : false"
            placeholder="请输入赛程信息"
            clearable
            style="width: 220px"
            @change="
              () => {
                form.match_nick = form.match_nick
              }
            "
          />
        </el-form-item>
        <el-form-item label="方案过期时间" prop="expires_time">
          <el-date-picker
            v-model="form.expires_time"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择过期时间"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <div class="w-full mb-2">
            <el-input
              v-model="form.price"
              placeholder="请输入价格"
              style="width: 220px"
              @input="
                () => {
                  if (
                    [0, 5, 10, 28, 38, 58, 88, 188, 288, 388, 488, 688, 888].includes(
                      form.price * 1
                    )
                  )
                    price = form.price * 1
                  else price = ''
                  getPrice(form.price)
                }
              "
            />
          </div>
          <el-radio-group
            v-model="price"
            is-button
            @change="
              () => {
                form.price = price
                getPrice(price)
              }
            "
          >
            <el-radio-button :value="0">免费</el-radio-button>
            <el-radio-button :value="88">88元</el-radio-button>
            <el-radio-button :value="188">188元</el-radio-button>
            <el-radio-button :value="288">288元</el-radio-button>
            <el-radio-button :value="388">388元</el-radio-button>
            <el-radio-button :value="488">488元</el-radio-button>
            <el-radio-button :value="688">688元</el-radio-button>
            <el-radio-button :value="888">888元</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="是否退款">
          <el-select placeholder="请选择是否退款" style="width: 220px">
            <el-option label="无退款" value="-" />
            <el-option label="不中补" value="-" />
            <el-option label="不中退" value="-" />
          </el-select>
        </el-form-item> -->
        <el-form-item v-if="marketData.length" label="营销方案" prop="description">
          <el-checkbox-group v-model="form.market_ids">
            <el-checkbox
              v-for="(item, index) in marketData"
              :key="index"
              :label="item.title"
              :value="item.id"
              :disabled="item.is_open == 1"
              @change="marketDataChange"
            >
              <div style="display: flex; align-items: center">
                {{ item.title }}
                <el-tooltip
                  class="box-item"
                  :content="item.rule"
                  effect="light"
                  raw-content
                  placement="top-start"
                >
                  <el-icon class="ml-0.5" color="#fea808" size="18"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          prop="match_data"
          required
          v-if="form.market_ids.includes(6)"
          label="图表赛程"
        >
          <!-- {{form.match_data}} -->
          <el-select
            v-model="form.match_data"
            filterable
            clearable
            placeholder="请选择"
            @change="radarChartChange"
            style="width: 220px"
            @clear="
              () => {
                form.match_data = ''
                form.kuiper_data = ''
                getMatch()
              }
            "
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!form.kuiper_data.length && form.market_ids.includes(6)" label="">
          <el-alert :closable="false" title="本场赛事无图表分析" type="warning" />
        </el-form-item>
        <el-form-item v-if="form.kuiper_data.length && form.market_ids.includes(6)" label="">
          <el-alert
            :closable="false"
            :title="`本场赛事占比：主队${form.kuiper_data[0].bar}% vs 客队${form.kuiper_data[1].bar}%`"
            type="success"
          />
        </el-form-item>
        <el-form-item v-if="form.market_ids.includes(5)" label="秒杀价格" prop="seckill_price">
          <el-input
            v-model="form.seckill_price"
            placeholder="请输入秒杀价格"
            clearable
            type="number"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item v-if="form.market_ids.includes(5)" label="秒杀结束时间" prop="seckill_expire">
          <el-date-picker
            v-model="form.seckill_expire"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择过期时间"
          />
        </el-form-item>
        <el-form-item v-if="form.market_ids.includes(5)" label="秒杀总数">
          <el-input
            v-model="form.seckill_stock"
            placeholder="请输入秒杀库存"
            clearable
            type="number"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item v-if="form.content_id && form.market_ids.includes(5)" label="虚拟库存">
          <el-input
            v-model="form.surplus_show"
            placeholder="请输入虚拟总数"
            clearable
            type="number"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <RichEditor v-model="form.description" />
        </el-form-item>
        <el-form-item prop="content">
          <div
            class="uploadImg"
            @click="
              () => {
                contentFileDialog = true
                uploadFileType = 'description'
              }
            "
          >
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            <div>上传图片</div>
          </div>
          <div
            v-for="(item, index) in form.img_url_list"
            :key="index"
            style="
              width: 98px;
              height: 98px;
              margin-right: 16px;
              margin-bottom: 16px;
              position: relative;
              border: 1px dashed #ccc;
            "
          >
            <!-- <el-icon size="20" color="#1a1a1a" style="position: absolute;right: -10px;top: -10px;z-index: 9;"><CircleCloseFilled /></el-icon> -->
            <img
              src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/close.png"
              style="
                width: 20px;
                height: 20px;
                position: absolute;
                right: -8px;
                top: -8px;
                z-index: 9;
                cursor: pointer;
              "
              @click="deleImg(index, 'description')"
              alt=""
            />
            <el-image
              style="width: 100%; height: 100%"
              :src="item"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :infinite="false"
              :preview-src-list="form.img_url_list"
              :initial-index="index"
              fit="cover"
            />
          </div>
        </el-form-item>
        <el-form-item label="付费正文" prop="content">
          <RichEditor v-model="form.content" />
        </el-form-item>
        <el-form-item prop="content">
          <div
            class="uploadImg"
            @click="
              () => {
                contentFileDialog = true
                uploadFileType = 'content'
              }
            "
          >
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            <div>上传图片</div>
          </div>
          <div
            v-for="(item, index) in form.img_url_list_main"
            :key="index"
            style="
              width: 98px;
              height: 98px;
              margin-right: 16px;
              margin-bottom: 16px;
              position: relative;
              border: 1px dashed #ccc;
            "
          >
            <!-- <el-icon size="20" color="#1a1a1a" style="position: absolute;right: -10px;top: -10px;z-index: 9;"><CircleCloseFilled /></el-icon> -->
            <img
              src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/close.png"
              style="
                width: 20px;
                height: 20px;
                position: absolute;
                right: -8px;
                top: -8px;
                z-index: 9;
                cursor: pointer;
              "
              @click="deleImg(index, 'content')"
              alt=""
            />
            <el-image
              style="width: 100%; height: 100%"
              :src="item"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :infinite="false"
              :preview-src-list="form.img_url_list_main"
              :initial-index="index"
              fit="cover"
            />
          </div>
        </el-form-item>
        <el-form-item label="是否置顶" prop="is_top">
          <el-switch
            v-model="form.is_top"
            class="ml-2"
            :active-value="1"
            :inactive-value="0"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </el-form-item>
        <el-form-item label="所属公众号" prop="wechat_id">
          <el-radio-group v-model="form.wechat_id" :disabled="form.content_id != ''" class="ml-4">
            <el-radio
              v-for="(value, key) of wechat_list"
              :key="key"
              :value="value.wechat_id"
              size="large"
              >{{ value.title }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="屏蔽谁" prop="invisible_ids">
          <el-input
            :modelValue="
              form.invisible_ids.length
                ? `含[${form.invisible_ids[0].nickname}...] 共${form.invisible_ids.length}人`
                : '请选择用户'
            "
            placeholder="请选择屏蔽用户"
            clearable
            readonly
            style="width: 220px"
            @click="
              () => {
                invisibleVisible = true
              }
            "
          />
        </el-form-item>
        <el-form-item label="发布时间" prop="release_time">
          <div class="w-full mb-2">
            <el-date-picker
              v-model="form.release_time"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请设置发布时间"
            />
          </div>
          <el-switch
            v-if="!form.draft_status"
            v-model="isPushFans"
            class="ml-2"
            :active-value="1"
            :inactive-value="0"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
          <div v-if="!form.draft_status" class="ml-2">是否同时通知已购买的粉丝</div>
        </el-form-item>
        <el-form-item label="海报样式" prop="poster_info">
          <div class="Grid poster-box">
            <div
              v-for="(value, key) of posterMap"
              :key="key"
              :class="['mr-2 poster-box-item']"
              @click="
                () => {
                  selectIndex = key
                  form.poster_info = key
                }
              "
            >
              <el-image
                :class="{ active: key == selectIndex }"
                style="width: 80px; height: 116px"
                :src="form.url ? form.url : value[category_ids]"
                fit="scale-down"
              />
              <div>
                <el-button
                  v-if="form.url"
                  style="cursor: pointer"
                  @click="
                    () => {
                      form.url = ''
                    }
                  "
                  >还原默认</el-button
                >
                <el-button style="cursor: pointer" @click="fileDialog = true">自定义背景</el-button>
                <div>尺寸:360*530 / 720*1060</div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="
              () => {
                resetForm()
                $emit('handleClose')
              }
            "
            >取消</el-button
          >
          <el-button
            v-if="form.draft_status && form.draft_status != 3"
            @click="
              () => {
                submit({ draft_status: 1 })
              }
            "
            >存草稿</el-button
          >
          <el-button
            type="danger"
            v-if="form.draft_status && form.draft_status != 3"
            @click="
              () => {
                submit({ draft_status: 3 })
              }
            "
            >存模板</el-button
          >
          <el-button
            v-if="!form.content_id || (form.draft_status && form.draft_status != 3)"
            type="primary"
            @click="
              () => {
                form.push_fans = 0
                submit({ draft_status: 0 })
              }
            "
            >发布</el-button
          >
          <el-button
            v-if="!form.content_id || (form.draft_status && form.draft_status != 3)"
            type="primary"
            @click="
              () => {
                form.push_fans = 1
                submit({ draft_status: 0 })
              }
            "
            >发布并通知</el-button
          >
          <el-button
            v-if="form.content_id && (form.draft_status == 0 || form.draft_status == 3)"
            type="primary"
            @click="
              () => {
                if (isPushFans) {
                  form.push_fans = 2
                } else {
                  form.push_fans = 1
                }
                submit({ draft_status: form.draft_status })
              }
            "
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 屏蔽用户 -->
    <invisible
      :visible="invisibleVisible"
      :toggleSelectionList="form.invisible_ids"
      :param="{ wechat_id: form.wechat_id }"
      @handle-close="invisibleVisible = false"
      @handle-complete="handleInvisibleComplete"
    />
    <!-- 付费正文-上传图片墙 -->
    <el-dialog
      v-model="contentFileDialog"
      :title="fileTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      top="1vh"
      width="80%"
      append-to-body
    >
      <FileManage
        :file-type="fileType"
        :isAll="false"
        @file-cancel="contentFileDialog = false"
        @file-submit="contentFileSubmit"
      />
    </el-dialog>
    <!-- 文件管理 -->
    <el-dialog
      v-model="fileDialog"
      :title="fileTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      top="1vh"
      width="80%"
      append-to-body
    >
      <FileManage
        :file-type="fileType"
        :fileSelectType="fileSelectType"
        :isAll="false"
        @file-cancel="fileDialog = false"
        @file-submit="fileSubmit"
      />
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import RichEditor from '@/components/RichEditor/index.vue'
import Invisible from './invisible.vue'
import dayjs from 'dayjs'
import FileManage from '@/components/FileManage/index.vue'
import { add, edit, marketList, kuiperMarket } from '@/api/content/content'
// import poster_1 from '@/assets/images/poster/1@2x.png'
// import poster_2 from '@/assets/images/poster/2@2x.png'
// import poster_3 from '@/assets/images/poster/3@2x.png'
// import poster_4 from '@/assets/images/poster/4@2x.png'
// import poster_1_1 from '@/assets/images/poster/1_1.png'
// import poster_1_2 from '@/assets/images/poster/1_2.png'
import { useUserStoreHook } from '@/store/modules/user'
import { babelParse } from 'vue/compiler-sfc'
import _ from 'lodash'
export default {
  name: 'AddEdit',
  components: { RichEditor, Invisible, FileManage },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  
  data() {
    return {
      uploadFileType: '',
      marketData: [], //营销方案列表
      market_ids: [], //选中的id
      marketDataList: [], //选中的id
      fileDialog: false, //文件管理弹窗
      fileSelectType: 'radio', //文件选择类型，单选---多选
      fileType: 'image', //文件类型
      today: dayjs().format('YYYY-MM-DD'), //今天
      tomorrow: dayjs().add(1, 'day').format('YYYY-MM-DD'), //明天
      theday: dayjs().add(2, 'day').format('YYYY-MM-DD'), //后天
      checked: false, //自定义标识
      isPushFans: 0, //是否开启发布时间
      dialogVisible: false,
      invisibleVisible: false, //屏蔽弹窗
      contentFileDialog: false, //付费正文上传文件弹窗
      // 价格选择
      price: 288,
      // 分类Id
      category_ids: 3,
      form: {
        content_id: '', // 方案id
        // 赛程日期
        match_date: dayjs().format('YYYY-MM-DD'),
        category_ids: [], // 类型：3 足球 4 篮球
        name: '',
        title: '', // 方案标题
        expires_time: '', // 方案过期时间
        match_info: '', // 方案关联的赛事(json)
        price: 288, // 价格
        img_url_list: [], //简介图片墙
        img_url: '',
        img_url_list_main: [], //付费图片墙
        img_main: '',
        url: '', //海报模板
        description: '', // 方案描述
        content: '', // 方案付费内容
        is_top: 0, // 是否置顶，1是0否
        is_hot: 0, // 是否热门，1是0否
        is_rec: 0, // 是否推荐，1是0否
        is_disable: 0, // 是否禁用，1是0否
        wechat_id: '', // 方案关联公众号
        invisible_ids: [], // 屏蔽不让查看的会员id,逗号分割
        release_time: '', // 定时发布时间
        push_fans: 0, // 方案发布时是否向粉丝推送(1-推送,0-不推送)
        poster_info: 1, // 海报信息
        draft_status: 1, // 草稿状态(1-是,0-否)
        match_nick: '',
        market_ids: [], //营销方案
        seckill_price: null, //秒杀价格
        seckill_expire: '', //秒杀时间
        seckill_stock: null, //秒杀库存
        surplus_show: null, //虚拟总数
        hits_show: '', //不知道啥就是要传这个字段
        kuiper_data: [], //图表数据
        match_data: '' //赛事图表
      },
      // 海报选择
      selectIndex: 1,
      posterMap: {
        1: {
          3: 'https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/poster/1_1.png',
          4: 'https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/poster/1_2.png'
        }
        // 2: {
        //   src: poster_2
        // },
        // 3: {
        //   src: poster_3
        // },
        // 4: {
        //   src: poster_4
        // }
      },
      // 赛事接口配置
      matchApi: {
        3: 'http://goalapi.feiyanfly.com/api/match/footballMatchList',
        4: 'http://goalapi.feiyanfly.com/api/match/basketballMatchList'
      },
      // 赛程集合
      options: [],
      // 公众号集合
      wechat_list: [],
      // 存储历史选择赛程信息
      historyMatchInfo: {
        match_info: '',
        match_nick: '',
        expires_time: ''
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      this.resetForm()
    }
  },
  mounted() {},
  methods: {
    // 针对营销方案做金额判断
    getPrice(e) {
      let that = this
      if (that.marketData.length) {
        that.marketDataList = _.cloneDeep(that.marketData)
      }
      if (that.form.market_ids.length) {
        that.market_ids = _.cloneDeep(that.form.market_ids)
      }
      if (Number(e) > 0) {
        that.form.market_ids = that.market_ids
        that.marketData = that.marketDataList
      } else {
        that.form.market_ids = []
        that.marketData = []
      }
    },
    // 营销列表
    marketList() {
      marketList().then((res) => {
        let list = []
        this.marketData = res.data.filter((i) => {
          if (i.is_enable && i.is_open && !this.form.market_ids.includes(i.id)) {
            this.form.market_ids.push(i.id)
          }
          return i.is_enable == 1
        })
        this.getPrice(this.form.price)
      })
    },
    // 关闭弹窗
    beforeClose() {
      ElMessageBox.confirm('是否关闭?')
        .then(() => {
          this.resetForm()
          this.$emit('handleClose')
        })
        .catch(() => {})
    },
    // 文件选择回调
    fileSubmit(files) {
      this.form.url = files[0]['file_url']
      this.fileDialog = false
    },
    // 照片上传回调
    contentFileSubmit(files) {
      if (this.uploadFileType == 'content') {
        files.forEach((element) => {
          this.form.img_url_list_main.push(element['file_url'])
        })
        this.form.img_url_list_main = [...new Set(this.form.img_url_list_main)]
        this.contentFileDialog = false
      } else {
        files.forEach((element) => {
          this.form.img_url_list.push(element['file_url'])
        })
        this.form.img_url_list = [...new Set(this.form.img_url_list)]
        this.contentFileDialog = false
      }
    },
    // 金额
    amount(rule, value, callback) {
      if (value === '') return callback(new Error('输入金额有误!'))
      if (/^[1-9]\d*(,\d{3})*(\.\d{1,2})?$|^0\.\d{1,2}$/.test(value) || value == 0) {
        callback()
      } else {
        callback(new Error('输入金额有误!'))
      }
    },
    // 文字检测
    detectionText (rule, value, callback) {
      console.log(rule, value, callback, 'rule, value, callback')
    },
    // Dialog打开回调
    initData() {
      const userStore = useUserStoreHook()
      this.wechat_list = userStore.user.wechat_list
      this.form.wechat_id = this.wechat_list.length != 0 ? this.wechat_list[0].wechat_id : ''
      if (Object.keys(this.data).length) {
        this.form = this.data
        this.checked = this.form.match_info == '' ? true : false
        // 初始化数据
        this.category_ids = this.form.category_ids[0]
        let data = this.form.match_info ? this.form.match_info : this.form.match_data
        if (data) {
          let v = JSON.parse(data)
          this.options = [
            {
              value: JSON.stringify({
                match_id: v.match_id,
                match_time: v.match_time,
                home_team_info: v.home_team_info,
                away_team_info: v.away_team_info,
                competition_info: v.competition_info
              }),
              label: `赛事:${v.competition_info.name}, 主队:[${v.home_team_info.team_name}] VS 客队:[${v.away_team_info.team_name}],赛事时间：${v.match_time}`
            }
          ]
        }
        if ([0, 5, 10, 28, 38, 58, 88, 188, 288, 388, 488, 688, 888].includes(this.form.price * 1))
          this.price = this.form.price * 1
        else this.price = ''
        this.selectIndex = this.form.poster_info
      } else {
        // 加载当天赛事
        this.getMatch()
      }
      this.marketList()
    },
    getMatch() {
      this.form.category_ids = [this.category_ids]
      this.form.match_info = ''
      this.form.match_data = ''
      axios({
        url: this.matchApi[this.form.category_ids],
        method: 'post',
        data: {
          search_day: this.form.match_date,
          search_type: 4
        },
        headers: { 'Content-Type': undefined }
      }).then((response) => {
        if (response.status === 200) {
          if (response.data.code == 1) {
            this.options = response.data.data.map((item) => {
              return {
                value: JSON.stringify({
                  match_id: item.match_id,
                  match_time: dayjs(item.match_time * 1000).format('YYYY-MM-DD HH:mm:ss'),
                  home_team_info: item.home_team,
                  away_team_info: item.away_team,
                  competition_info: item.competition
                }),
                label: `赛事:${item.competition.name}, 主队:[${
                  item.home_team.team_name
                }] VS 客队:[${item.away_team.team_name}],赛事时间：${dayjs(
                  item.match_time * 1000
                ).format('YYYY-MM-DD HH:mm:ss')}`
              }
            })
          } else {
            this.$message.error(response.data.msg)
          }
        } else {
          this.$message.error('网络异常')
        }
      })
    },
    // 图表数据接口
    kuiperMarket(obj) {
      kuiperMarket(obj).then((res) => {
        if (res.code == 200) {
          this.form.kuiper_data = res.data
        }
      })
    },
    // 选中生成雷达图表
    radarChartChange() {
      if (this.form.match_data) {
        let item = JSON.parse(this.form.match_data)
        let obj = {
          match_id: item.match_id,
          match_type: this.form.category_ids[0] == 3 ? 1 : 2
        }
        this.kuiperMarket(obj)
      }
    },
    // 选中赛程
    handleMatchChange() {
      if (this.form.match_info) {
        this.form.match_data = this.form.match_info
        let item = JSON.parse(this.form.match_info)
        this.form.match_nick =
          item.home_team_info.team_name + ' VS ' + item.away_team_info.team_name
        // 赋值方案过期时间
        // 使用dayjs解析日期字符串
        const date = dayjs(item.match_time)
        // 加上一个小时
        const newDate = date.add(1, 'hour')
        this.form.expires_time = newDate.format('YYYY-MM-DD HH:mm:ss')
        let obj = {
          match_id: item.match_id,
          match_type: this.form.category_ids[0] == 3 ? 1 : 2
        }
        if (this.category_ids == 3) {
          this.kuiperMarket(obj)
        } else {
          this.form.kuiper_data = []
        }
      }
    },
    // 删除
    deleImg(index, type) {
      if (type == 'content') {
        this.form.img_url_list_main.splice(index, 1)
      } else {
        this.form.img_url_list.splice(index, 1)
      }
    },
    submit(obj) {
      // if ()
      if (obj.draft_status == 3) {
        this.submitSave(obj)
        return
      }
      this.$refs['ref'].validate((valid) => {
        if (valid) {
          if (!(this.form.price * 1) && !obj.draft_status) {
            ElMessageBox.confirm('此篇方案当前价格是免费?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.submitSave(obj)
            })
          } else {
            this.submitSave(obj)
          }
        } else {
          ElMessage.error('请完善必填项（带红色星号*）')
        }
      })
    },
    submitSave(obj) {
      if (obj) this.form.draft_status = obj.draft_status
      this.form.img_url = _.cloneDeep(this.form.img_url_list).join(',')
      this.form.img_main = _.cloneDeep(this.form.img_url_list_main).join(',')
      if (!Number(this.form.price) > 0) {
        this.form.market_ids = [] //营销方案
        this.form.seckill_price = null //秒杀价格
        this.form.seckill_expire = '' //秒杀时间
        this.form.seckill_stock = null //秒杀库存
        this.form.surplus_show = null //虚拟总数
      }
      if (this.form.content_id) {
        edit(this.form)
          .then((res) => {
            if (res.code == 200) {
              this.resetForm()
              this.$emit('handleComplete')
              this.$emit('handleClose')
              ElMessage.success(res.msg)
            }
          })
          .catch(() => {})
      } else {
        add(this.form)
          .then((res) => {
            if (res.code == 200) {
              this.resetForm()
              this.$emit('handleComplete')
              this.$emit('handleClose')
              ElMessage.success(res.msg)
            }
          })
          .catch(() => {})
      }
    },
    // 屏蔽谁回调
    handleInvisibleComplete(e) {
      this.form.invisible_ids = e
    },
    // 重置
    resetForm() {
      // this.$refs['ref'].resetFields()
      this.form = {
        content_id: '', // 方案id
        // 赛程日期
        match_date: dayjs().format('YYYY-MM-DD'),
        category_ids: [], // 类型：3 足球 4 篮球
        name: '',
        title: '', // 方案标题
        expires_time: '', // 方案过期时间
        match_info: '', // 方案关联的赛事(json)
        match_data: '', // 方案关联的赛事(json)
        price: 288, // 价格
        description: '', // 方案描述
        content: '', // 方案付费内容
        img_url_list: [], //付费图片
        img_url_list_main: [], //付费图片
        img_main: '', //正文付费图片墙
        img_url: '', //简介图片墙
        is_top: 0, // 是否置顶，1是0否
        is_hot: 0, // 是否热门，1是0否
        is_rec: 0, // 是否推荐，1是0否
        is_disable: 0, // 是否禁用，1是0否
        wechat_id: '', // 方案关联公众号
        invisible_ids: [], // 屏蔽不让查看的会员id,逗号分割
        release_time: '', // 定时发布时间
        push_fans: 0, // 方案发布时是否向粉丝推送(1-推送,0-不推送)
        poster_info: 1, // 海报信息
        draft_status: 1, // 草稿状态(1-是,0-否)
        match_nick: '',
        market_ids: [], //营销方案
        seckill_price: null, //秒杀价格
        seckill_expire: '', //秒杀时间
        seckill_stock: null, //秒杀库存
        surplus_show: null, //虚拟总数
        hits_show: '', //不知道啥就是要传这个字段
        kuiper_data: [] //图表数据
      }
      this.market_ids = []
      this.marketDataList = []
      this.checked = false
      this.selectIndex = 1
      this.isPushFans = 0
      this.price = 288
      this.category_ids = 3
      this.options = []
      this.wechat_list = []
      this.historyMatchInfo = {
        match_info: '',
        match_nick: '',
        expires_time: ''
      }
    },
    handleCheckBox() {
      if (this.checked) {
        // 存储历史选择赛程信息
        this.historyMatchInfo = {
          match_info: this.form.match_info,
          match_nick: this.form.match_nick,
          expires_time: this.form.expires_time
        }
        this.form.match_info = ''
        this.form.match_nick = ''
        this.form.expires_time = ''
        this.form.kuiper_data = []
        this.form.match_data = ''
      } else {
        this.form.match_info = this.historyMatchInfo.match_info
        this.form.match_nick = this.historyMatchInfo.match_nick
        this.form.expires_time = this.historyMatchInfo.expires_time
        this.form.kuiper_data = []
        this.form.match_data = ''
        // if (!this.options.length)
      }
      this.getMatch()
    },
    marketDataChange(e) {
      if (e && this.form.market_ids.includes(6)) {
        this.form.match_data = this.form.match_info
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.poster-box {
  &-item {
    cursor: pointer;
  }
  .active {
    border: 2px dashed #578bd6;
    padding: 2px;
  }
}
.uploadImg {
  border: 1px dashed var(--el-border-color);
  text-align: center;
  width: 98px;
  height: 98px;
  line-height: 28px;
  padding-top: 20px;
  margin-right: 12px;
  margin-bottom: 16px;
}
.countdown {
  font-size: 14px;
  background: rgb(228, 86, 86);
  padding: 4px;
  color: #fff;
  border-radius: 100px;
  .el-statistic__content {
    .el-statistic__number {
    }
  }
}
</style>
